# -*- coding: utf-8 -*-

# Copyright (C) 2017 Intel Corporation.  All rights reserved.
# Copyright (c) WanSheng Intelligent Corp. All rights reserved.

#
# Licensed under the Apache License, Version 2.0 (the "License");
#

import json

from ..model.resource_data_base import ResourceDataBase
from ..model.constants import MediaTypeFormat

class ResourceDataLWM2M(ResourceDataBase):
    def __init__(self, raw_payload, fmt):
        self.base_name = ""
        super(ResourceDataLWM2M, self).__init__(raw_payload, fmt)
        
    def get_format(self):
        return MediaTypeFormat.APPLICATION_JSON_LWM2M

    def pack(self):
        if len(self.items) == 0:
            return MediaTypeFormat.APPLICATION_JSON_LWM2M, "{\"e\":[]}"
        obj = {}
        json_array = []
        for item in self.items:
            data = item
            o = {}
            o["n"] =  data.prop_name
            if isinstance(data.value, bool):
                o["bv"] = data.value
            elif isinstance(data.value, float) or isinstance(data.value, int):
                o["v"] = data.value
            elif isinstance(data.value, str):
                o["sv"] = data.value
            else:
                pass
            if data.t:
                o["t"] = data.t
            json_array.append(o)
        obj["e"] = json_array
        
        if self.base_name != "":
            obj["bn"] = self.base_name
        return MediaTypeFormat.APPLICATION_JSON_LWM2M, json.dumps(obj)
